package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;


    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        List<Orders> list1 = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (list1 != null && list1.size() > 0) {
            list1.forEach(L1->{
                L1.setStatus(Orders.CANCELLED);
                L1.setCancelReason(MessageConstant.ORDER_TIMEOUT);
                L1.setOrderTime(LocalDateTime.now());
                orderMapper.update(L1);
            });
        }
    }


    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("定时处理已完成的订单：{}", LocalDateTime.now());
        List<Orders> list2 = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if (list2 != null && list2.size() > 0) {
            list2.forEach(L2 ->{
                L2.setStatus(Orders.COMPLETED);
                orderMapper.update(L2);
            });
        }
    }

}
